<template>
  <div>
    <el-alert title="查询信息" type="info" :closable="false"></el-alert>
    <el-form inline :model="form">
      <el-form-item label="用户名">
        <el-input
          v-model="form.userName"
          placeholder="请输入用户名"
          size="medium"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="info" size="medium" @click="search(1)">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="info" size="medium" @click="add">新增</el-button>
      </el-form-item>
    </el-form>
    <el-alert title="用户信息列表" type="info" :closable="false"></el-alert>
    <el-table :data="tableData" stripe v-loading="loading">
      <el-table-column
        label="用户名"
        prop="userName"
        align="center"
      ></el-table-column>
      <el-table-column
        label="单位"
        prop="company"
        align="center"
      ></el-table-column>
      <el-table-column
        label="职务"
        prop="post"
        align="center"
      ></el-table-column>
      <el-table-column
        label="用户类型"
        prop="memberTypes"
        align="center"
      ></el-table-column>
      <el-table-column
        label="真实姓名"
        prop="realName"
        align="center"
      ></el-table-column>
      <el-table-column
        label="角色名称"
        prop="roleName"
        align="center"
      ></el-table-column>
      <el-table-column
        label="电话"
        prop="phone"
        align="center"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        prop="createTime"
        align="center"
      ></el-table-column>
      <el-table-column
        label="有效期"
        prop="validTime"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.memberType == '01'">
            <el-link
              type="primary"
              :underline="false"
              @click="modify(scope.row)"
              >修改信息</el-link
            >&nbsp;
            <el-link type="primary" :underline="false" @click="del(scope.row)"
              >删除</el-link
            >&nbsp;
            <el-link type="primary" :underline="false" @click="reset(scope.row)"
              >重置密码</el-link
            >&nbsp;
            <el-link
              type="primary"
              :underline="false"
              @click="reBind(scope.row)"
              >重绑监测体</el-link
            >&nbsp;
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-row type="flex" justify="end">
      <el-col :span="10">
        <el-pagination
          background
          :current-page="pageData.currentPage"
          layout="total, prev, pager, next, jumper"
          :total="pageData.count"
          :page-size="pageData.pageSize"
          @current-change="handleCurrentChange"
          v-if="pageData.count && pageData.count != 0"
        >
        </el-pagination>
      </el-col>
    </el-row>
    <el-dialog title="增加用户" :visible.sync="addManager" width="25%">
      <el-form
        :model="addForm"
        ref="addForm"
        :rules="rules"
        size="medium"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="addForm.userName"
            placeholder="请输入用户名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户单位" prop="company">
          <el-input
            v-model="addForm.company"
            placeholder="请输入用户单位"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户职务" prop="post">
          <el-input
            v-model="addForm.post"
            placeholder="请输入用户职务"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="userPassword">
          <el-input
            v-model="addForm.userPassword"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="addForm.realName"
            placeholder="请输入真实姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="绑定角色">
          <el-select
            v-model="addForm.roleId"
            placeholder="请选择角色"
            style="display: flex"
          >
            <el-option label="操作员" :value="5"></el-option>
            <el-option label="管理员" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效期">
          <el-date-picker
            v-model="addForm.validTime"
            type="date"
            placeholder="请选择有效期"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addManager = false">取 消</el-button>
        <el-button type="primary" @click="handle">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="修改管理员" :visible.sync="modifyManager" width="25%">
      <el-form
        :model="modifyForm"
        ref="modifyForm"
        :rules="rules"
        size="medium"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="modifyForm.userName"
            placeholder="请输入用户名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户单位" prop="company">
          <el-input
            v-model="modifyForm.company"
            placeholder="请输入用户单位"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户职务" prop="post">
          <el-input
            v-model="modifyForm.post"
            placeholder="请输入用户职务"
          ></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="modifyForm.realName"
            placeholder="请输入真实姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input
            v-model="modifyForm.phone"
            placeholder="请输入电话"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select
            v-model="modifyForm.roleId"
            placeholder="请选择角色"
            style="display: flex"
          >
            <el-option label="操作员" :value="5"></el-option>
            <el-option label="管理员" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="有效期">
          <el-date-picker
            v-model="modifyForm.validTime"
            type="date"
            placeholder="请选择有效期"
            readonly
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="modifyManager = false">取 消</el-button>
        <el-button type="primary" @click="handle2">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="绑定监测体菜单" :visible.sync="bindMonitor" width="20%">
      <el-tree
        :data="treeData"
        show-checkbox
        node-key="id"
        :default-checked-keys="defaultCheckedKeys"
        ref="tree"
        :props="defaultProps"
      >
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bindMonitor = false">取 消</el-button>
        <el-button type="primary" @click="handle3">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Axios from "axios";
import moment from "moment";
import * as serviceApi from "../../common/service.config";
Axios.defaults.withcredentials = true;

export default {
  name: "UserManagement",
  data() {
    return {
      form: {
        userName: "",
      },
      tableData: null,
      pageData: {
        currentPage: null,
        count: null,
        pageSize: null,
      },
      addManager: false,
      addForm: {
        userName: "",
        company: "",
        post: "",
        userPassword: "",
        realName: "",
        phone: "",
        roleId: "",
        validTime: "",
      },
      modifyManager: false,
      modifyForm: {
        userName: "",
        company: "",
        post: "",
        realName: "",
        phone: "",
        roleId: "",
        validTime: "",
      },
      bindMonitor: false,
      treeData: null,
      defaultProps: {
        label: "name",
      },
      defaultCheckedKeys: [],
      managerId: null,
      rules: {
        userName: [
          {
            pattern: /^[a-zA-z][a-zA-Z0-9_]{3,20}$/,
            message: "用户名必须(4-20)位的字母、数字组合!",
            trigger: "blur",
          },
        ],
        company: [
          {
            pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
            message: "不支持特殊字符！",
            trigger: "blur",
          },
        ],
        post: [
          {
            pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
            message: "不支持特殊字符！",
            trigger: "blur",
          },
        ],
        userPassword: [
          {
            pattern: /^\w{6,20}$/,
            message: "密码必须是(6-20)位字母、数字和下划线组合(不含空格)!",
            trigger: "blur",
          },
        ],
        realName: [
          {
            pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9.·-]+$/,
            message: "不支持特殊字符！",
            trigger: "blur",
          },
        ],
        phone: [
          {
            pattern: /^((13|14|15|16|17|18)[0-9]{1}\d{8})|((166|199|198)[0-9]{1}\d{7})$/,
            message: "请输入正确的手机号码！",
            trigger: "blur",
          },
        ],
      },
      loading: null,
    };
  },
  methods: {
    queryManagerList(queryData) {
      this.loading = true;
      Axios({
        url: serviceApi.KB_API,
        method: "post",
        data: `appMsg={"parameter":"{\\"page\\":{\\"currentPage\\":${queryData.currentPage},\\"pageSize\\":10},\\"area\\":\\"\\",\\"orgName\\":\\"\\",\\"userName\\":\\"${queryData.userName}\\"}","serviceCode":"listManagerInfoByPage","timestamp":"","uuid":""}`,
      }).then((res) => {
        this.loading = false;
        this.pageData = res.data.parameter.page;
        let list = res.data.parameter.list;
        for (let i = 0; i < list.length; i++) {
          list[i].createTime = moment(list[i].createTime).format(
            "YYYY-MM-DD HH:mm:ss"
          );
          if (list[i].validTime) {
            list[i].validTime = moment(list[i].validTime).format("YYYY-MM-DD");
          } else {
            list[i].validTime = "-";
          }
          if (list[i].memberType == "01") {
            list[i].memberTypes = "操作员";
          } else if (list[i].memberType == "00") {
            list[i].memberTypes = "管理员";
          }
        }
        this.tableData = list;
      });
    },
    search(currentPage) {
      let queryData = {
        currentPage: currentPage,
        userName: this.form.userName,
      };
      this.queryManagerList(queryData);
    },
    handleCurrentChange(val) {
      this.search(val);
    },
    bindUser(queryData) {
      this.bindMonitor = true;
      Axios({
        url: serviceApi.KB_API,
        method: "post",
        data: `appMsg={"parameter":"{\\"phone\\":\\"${queryData.phone}\\",\\"realName\\":\\"${queryData.realName}\\",\\"userName\\":\\"${queryData.userName}\\",\\"company\\":\\"${queryData.company}\\",\\"post\\":\\"${queryData.post}\\",\\"userPassword\\":\\"${queryData.userPassword}\\",\\"roleId\\":\\"${queryData.roleId}\\",\\"validTime\\":\\"${queryData.validTime}\\"}","serviceCode":"getManagerId","timestamp":"","uuid":""}`,
      }).then((res) => {
        let managerId = res.data.parameter.managerId;
        this.managerId = managerId;
        this.setTree(managerId);
      });
    },
    setTree(managerId) {
      Axios({
        url: serviceApi.KB_API,
        method: "post",
        data: `appMsg={"parameter":"{\\"managerId\\":${managerId}}","serviceCode":"listManagerMonitor","timestamp":"","uuid":""}`,
      }).then((res) => {
        (this.treeData = null), (this.defaultCheckedKeys = []);
        let list = res.data.parameter.list;
        for (let i = 0; i < list.length; i++) {
          if (list[i].checked == "true") {
            this.defaultCheckedKeys.push(list[i].id);
          }
        }
        this.treeData = list;
        let queryDatas = {
          userName: "",
          currentPage: "1",
        };
        this.queryManagerList(queryDatas);
      });
    },
    add() {
      this.addManager = true;
      this.addForm = {
        userName: "",
        company: "",
        post: "",
        userPassword: "",
        realName: "",
        phone: "",
        roleId: "",
        validTime: "",
      };
    },
    handle() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          this.addManager = false;
          let queryData = {
            company: this.addForm.company,
            phone: this.addForm.phone,
            post: this.addForm.post,
            realName: this.addForm.realName,
            roleId: this.addForm.roleId,
            userName: this.addForm.userName,
            userPassword: this.addForm.userPassword,
            validTime: moment(this.addForm.validTime).format("YYYY-MM-DD"),
          };
          Axios({
            url: serviceApi.KB_API,
            method: "post",
            data: `appMsg={"parameter":"{\\"company\\":\\"${queryData.company}\\",\\"post\\":\\"${queryData.post}\\",\\"realName\\":\\"${queryData.realName}\\",\\"roleId\\":\\"${queryData.roleId}\\",\\"userName\\":\\"${queryData.userName}\\",\\"userPassword\\":\\"${queryData.userPassword}\\",\\"validTime\\":\\"${queryData.validTime}\\",\\"phone\\":\\"${queryData.phone}\\",}","serviceCode":"addManagerInfo","timestamp":"","uuid":""}`,
          }).then((res) => {
            let status = res.data.parameter.status;
            let message = res.data.parameter.message;
            if (status == "0000") {
              let success = confirm("新增用户成功，是否绑定监测体");
              if (success == true) {
                this.bindUser(queryData);
              } else {
                let queryDatas = {
                  userName: "",
                  currentPage: "1",
                };
                this.queryManagerList(queryDatas);
              }
            } else {
              this.$message({
                message: message,
                type: "warning",
              });
            }
          });
        }
      });
    },
    modify(row) {
      this.modifyManager = true;
      this.modifyForm = Object.assign({}, row);
      this.modifyForm.roleId = Number(row.roleId);
    },
    handle2() {
      this.$refs["modifyForm"].validate((valid) => {
        if (valid) {
          this.modifyManager = false;
          let queryData = {
            company: this.modifyForm.company,
            phone: this.modifyForm.phone,
            post: this.modifyForm.post,
            realName: this.modifyForm.realName,
            roleId: this.modifyForm.roleId,
            userName: this.modifyForm.userName,
            validTime: moment(this.modifyForm.validTime).format("YYYY-MM-DD"),
            userPassword: this.modifyForm.userPassword,
            memberType: this.modifyForm.memberType,
            id: this.modifyForm.id,
          };
          Axios({
            url: serviceApi.KB_API,
            method: "post",
            data: `appMsg={"parameter":"{\\"company\\":\\"${queryData.company}\\",\\"post\\":\\"${queryData.post}\\",\\"realName\\":\\"${queryData.realName}\\",\\"roleId\\":\\"${queryData.roleId}\\",\\"userName\\":\\"${queryData.userName}\\",\\"validTime\\":\\"${queryData.validTime}\\",\\"phone\\":\\"${queryData.phone}\\",\\"userPassword\\":\\"${queryData.userPassword}\\",\\"memberType\\":\\"${queryData.memberType}\\",\\"id\\":\\"${queryData.id}\\"}","serviceCode":"updateManagerInfo","timestamp":"","uuid":""}`,
          }).then((res) => {
            let status = res.data.parameter.status;
            let message = res.data.parameter.message;
            if (status == "0000") {
              this.$message({
                message: message,
                type: "success",
                duration: 1000,
                onClose: () => {
                  let queryDatas = {
                    userName: "",
                    currentPage: "1",
                  };
                  this.queryManagerList(queryDatas);
                },
              });
            } else {
              this.$message({
                message: message,
                type: "warning",
              });
            }
          });
        }
      });
    },
    del(row) {
      this.$confirm("您确定要删除该条数据吗？", "删除用户", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          Axios({
            url: serviceApi.KB_API,
            method: "post",
            data: `appMsg={"parameter":"{\\"managerId\\":\\"${row.id}\\",\\"memberType\\":\\"${row.memberType}\\"}","serviceCode":"deleteManagerInfo","timestamp":"","uuid":""}`,
          }).then((res) => {
            let message = res.data.parameter.message;
            this.$message({
              type: "success",
              message: message,
              duration: 1000,
              onClose: () => {
                let queryData = {
                  currentPage: "1",
                  userName: "",
                };
                this.queryManagerList(queryData);
              },
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消删除!",
          });
        });
    },
    reset(row) {
      Axios({
        url: serviceApi.KB_API,
        method: "post",
        data: `appMsg={"parameter":"{\\"id\\":\\"${row.id}\\",\\"memberType\\":\\"${row.memberType}\\"}","serviceCode":"resetPassWord","timestamp":"","uuid":""}`,
      }).then((res) => {
        let message = res.data.parameter.message;
        this.$message({
          message: message,
          type: "success",
          duration: 1000,
        });
      });
    },
    reBind(row) {
      this.bindMonitor = true;
      this.managerId = row.id;
      this.setTree(row.id);
    },
    handle3() {
      this.bindMonitor = false;
      let arr = this.$refs.tree.getCheckedKeys();
      arr = JSON.stringify(arr);
      arr = arr.replace(/\"/g, '\\"');
      Axios({
        url: serviceApi.KB_API,
        method: "post",
        data: `appMsg={"parameter":"{\\"managerId\\":\\"${this.managerId}\\",\\"monitorIds\\":${arr}}","serviceCode":"bindManagerMonitor","timestamp":"","uuid":""}`,
      }).then((res) => {
        let resultCode = res.data.resultcode;
        let message = res.data.parameter.message;
        if (resultCode == "0000") {
          this.$message({
            message: message,
            type: "success",
          });
        } else {
          this.$message({
            message: message,
            type: "warning",
          });
        }
      });
    },
  },
  created() {
    let queryData = {
      userName: "",
      currentPage: "1",
    };
    this.queryManagerList(queryData);
  },
};
</script>

<style lang="less" scoped>
.el-alert {
  line-height: 30px;
  margin-top: 20px;
  /deep/ .el-alert__title {
    font-size: 16px;
  }
}
.el-form {
  margin: 20px 0;
  margin-left: 30px;
}
</style>